package com.pj.point.self;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.pj.point.R;

public class ChangePassword extends AppCompatActivity {

    private EditText oldPassword;
    private EditText newPassword;
    private EditText newPasswordAgain;
    private Button changePasswordBt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);
        ActionBar bar = getSupportActionBar();
        bar.setTitle("修改密码");
        bar.setDisplayHomeAsUpEnabled(true);
        initView();
        changePasswordBt.setOnClickListener(view -> {
            String old = oldPassword.getText().toString().trim();
            String news = newPassword.getText().toString().trim();
            String newsAgain = newPasswordAgain.getText().toString().trim();
            if(old.equals("") || news.equals("") || newsAgain.equals("")){
                Toast.makeText(this, "请填完整写所需要输入的信息", Toast.LENGTH_SHORT).show();
                return;
            }
            if(!news.equals(newsAgain)){
                Toast.makeText(this, "两次新密码不相同，请重新输入", Toast.LENGTH_SHORT).show();
                newPasswordAgain.setText("");
                newPassword.setText("");
                return;
            }
            SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
            if (!sharedPreferences.getString("password","").equals(old)){
                Toast.makeText(this, "旧密码不正确", Toast.LENGTH_SHORT).show();
                return;
            }
            SharedPreferences.Editor data = sharedPreferences.edit();
            data.putString("password",news).apply();
            Toast.makeText(this, "修改成功！", Toast.LENGTH_SHORT).show();
            finish();
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        finish();
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        oldPassword = (EditText) findViewById(R.id.old_password);
        newPassword = (EditText) findViewById(R.id.new_password);
        newPasswordAgain = (EditText) findViewById(R.id.new_password_again);
        changePasswordBt = (Button) findViewById(R.id.change_password_bt);
    }
}